package com.sgb.contract.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.swgk.core.dialog.DialogHelper;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;

/**
 * 合同组件sdk初始化
 * @author cyj
 */
public final class ContractSdk implements Application.ActivityLifecycleCallbacks {

    private static volatile Application mApplicationContext;
    private WeakReference<Activity> mTopActivity;

    private static class SingletonHolder {
        private static final ContractSdk INSTANCE = new ContractSdk();
    }

    private ContractSdk() {}

    public static ContractSdk getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static Application getApplication() {
        return mApplicationContext;
    }

    /**
     * 初始化
     * @param context    Context
     */
    public synchronized void init(@NonNull @NotNull Context context) {
        if(mApplicationContext != null) {
            return;
        }
        mApplicationContext = (Application) context.getApplicationContext();
        // 注册activity生命周期
        mApplicationContext.registerActivityLifecycleCallbacks(this);
    }

    /**
     * 获取当前activity活动
     * @return    Activity
     */
    public Activity getTopActivity() {
        return mTopActivity == null ? null : mTopActivity.get();
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        // Call after super.onCreate
        if (mTopActivity != null) {
            mTopActivity.clear();
        }
        mTopActivity = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {}

    @Override
    public void onActivityResumed(Activity activity) {
        // Call after super.onResumed
        if (null != mTopActivity.get() && !mTopActivity.get().equals(activity)) {
            mTopActivity.clear();
            mTopActivity = new WeakReference<>(activity);
        }
    }

    @Override
    public void onActivityPaused(Activity activity) {}

    @Override
    public void onActivityStopped(Activity activity) {}

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

    @Override
    public void onActivityDestroyed(Activity activity) {}
}
